package cn.xiaolang.thread.concurrent;

/**
 * <p>
 * 多生产多消费（@since JDK 1.5  Lock,Condition机制）
 * <p>
 * Lock锁代替了synchronized同步代码块的书写
 * Condition代替了同步代码块中锁对象上的等待唤醒(await ,signal)
 *
 * @author DeanKano
 * @date 2016年12月18日 下午12:59:19
 */
public class ProduceConsumerLockCondition {

    public static void main(String[] args) {
        ShareResource resource = new ShareResource();
        new Thread(new Producer(resource), "P1").start();
        new Thread(new Producer(resource), "P2").start();
        new Thread(new Producer(resource), "P3").start();
        new Thread(new Consumer(resource), "C1").start();
        new Thread(new Consumer(resource), "C2").start();
    }

    static class Producer implements Runnable {

        private ShareResource resource;

        public Producer(ShareResource resource) {
            super();
            this.resource = resource;
        }

        @Override
        public void run() {
            int num = 1;
            while (true) {
                resource.putLockCondition(Thread.currentThread().getName() + num);
                num++;
            }
        }
    }

    static class Consumer implements Runnable {
        private ShareResource resource;

        public Consumer(ShareResource resource) {
            super();
            this.resource = resource;
        }

        @Override
        public void run() {
            while (true) {
                resource.gainLockCondition();
            }
        }
    }
}




